package cn.claim.storage.server;

import cn.claim.storage.tools.Config;
import cn.claim.storage.tools.FileInfoData;
import cn.claim.storage.tools.JSONParsable;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by claim on 17-7-13.
 */
public enum DataManager {
    DATABASE;
    private final String dir = Config.getProp("databaseDir", "./database/");

    public void update(String key, JSONParsable data) {
        File dataFile = new File(dir + key);
        PrintWriter writer = null;
        try {
            if (!dataFile.exists())
                //noinspection ResultOfMethodCallIgnored
                dataFile.createNewFile();
            writer = new PrintWriter(dataFile);
            writer.println(data.toJSON());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    public <T> T select(String key, Class<T> type) {
        File dataFile = new File(dir + key);
        if (!dataFile.exists())
            return null;
        FileReader reader = null;
        try {
            reader = new FileReader(dataFile);
            return JSONParsable.parse(reader, type);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public boolean delete(String key) {
        File data = new File(dir + key);
        return data.delete();
    }

    public <T> List<T> selectAll(Class<T> type) {
        List<T> allData = new ArrayList<>();
        File baseDir = new File(dir);
        String[] list = baseDir.list();
        for (String s : list) {
            allData.add(select(s, type));
        }
        return allData;
    }
}
